# coding:utf8
"""
get_sys_performance_info.py
获取系统性能信息
"""
import psutil
import datetime


def bytes_2_gb(bytes_):
    """
    字节转GB
    :return: 
    """
    return round(bytes_ / 10.0**9, 2)


def get_memory_use_info():
    """
    获取内存使用情况
    :return: mem
    """
    mem = psutil.virtual_memory()
    return [
        'memory_used_size: %sG' % round(mem.used / 10.0**9, 2),     # 内存使用
        'memory_total_size: %sG' % round(mem.total / 10.0**9, 2),   # 内存总大小
        'memory_percent: %s' % mem.percent + '%']                   # 内存使用率


def get_disk_used_info():
    """
    获取磁盘使用情况
    :return: disks_info
    """
    disk_partitions = psutil.disk_partitions()
    disks_info = []
    for partition in disk_partitions:
        disk_info = []
        if 'rw' in partition.opts:
            disk_used_info = psutil.disk_usage(partition.device)
            disk_info.append("%s disk total: %sG" % (
            partition.device.strip('\\'), round(disk_used_info.total / 10.0 ** 9, 2)))
            disk_info.append("disk used: %sG" % round(
                disk_used_info.used / 10.0 ** 9, 2))
            disk_info.append("disk free: %sG" % round(
                disk_used_info.free / 10.0 ** 9, 2))
            disk_info.append("disk percent: %s" %
                             disk_used_info.percent + "%")
            disks_info.append(", ".join(disk_info))
    return disks_info


def get_disk_io_info():
    """
    获取磁盘读写信息
    :return: 
    """
    disk_io_info = psutil.disk_io_counters()
    return ["read count: %s" % disk_io_info.read_count,
            "write count: %s" % disk_io_info.write_count,
            "read size: %sG" % round(disk_io_info.read_bytes / 10.0**9, 2),
            "write size: %sG" % round(disk_io_info.write_bytes / 10.0**9, 2),
            "read time: %s" % disk_io_info.read_time,
            "write time: %s" % disk_io_info.write_time]


def get_net_io_info():
    """
    获取网络读写
    :return: 
    """
    net_io_info = psutil.net_io_counters()
    return ["sent packet num: %s" % net_io_info.packets_sent,
            "recv packet num: %s" % net_io_info.packets_recv,
            "sent size: %sG" % round(net_io_info.bytes_sent / 10.0**9, 2),
            "recv size: %sG" % round(net_io_info.bytes_recv / 10.0**9, 2)]


def get_users_info():
    """
    获取用户开机时间
    :return: 
    """
    users_info = psutil.users()
    str_ = []
    for user_info in users_info:
        starttime = datetime.datetime.fromtimestamp(
            user_info.started).strftime("%Y-%m-%d %H:%M:%S")
        str_.append("user name: %s" % user_info.name)
        str_.append("user open machine time: %s" % starttime)
    return str_


def get_pids():
    """
    获取进程pid
    :return: 
    """
    return psutil.pids()


"""
get_sys_performance_info.py
"""